# -*- coding: utf-8 -*-
# @Author : HJH
# @Time : 2024/1/16 17:51
# @Use :
import datetime
import concurrent.futures
import os
import random
import sys
from urllib.parse import quote_plus
import pandas as pd
import requests
import hashlib
import time
import json

from loguru import logger
from pymongo import MongoClient
from tqdm import tqdm


def log_config():
    # 添加输出处理程序，将日志输出到文件
    logger.add("./logs/info_file.log", level="INFO")
    logger.add("./logs/error_file.log", level="ERROR")


def get_date_time(datetime_str):
    # 输入日期时间字符串
    # datetime_str = "2024-02-15 21:15:00"

    # 将日期时间字符串转换为datetime对象
    datetime_obj = datetime.datetime.strptime(datetime_str, "%Y-%m-%d %H:%M")

    # 获取当前时区的时间戳
    timestamp = datetime_obj.timestamp()

    # 将时间戳转换为整数
    timestamp = int(timestamp)

    # 在时间戳后面添加3个零，使其长度为13位
    return str(timestamp) + "000"


account_list = [
    # {"username": "18568550216", "password": "yuan2003"},
    # {"username": "17538938941", "password": "zhang123."},
    # {"username": "17603831169", "password": "789456ab"},
    {"username": "13783590698", "password": "789456ab"}
]


def send_request(flight_no, cabin, dep, arr, dep_time, arr_time):
    account = random.choice(account_list)

    appkey = "B20230907024"
    secret = "NoPt5JpRfRU6d4pR75Mz8nWdLQafhGbR"
    url = "http://openapi.tenfli.com/api/order/policies"
    req = {
        "accounts":
            [
                {
                    # "password": "789456ab",
                    "password": account['password'],
                    "supplierCode": "OTA_QUNAR",
                    # "username": "tb9071094764"
                    "username": account['username']
                }
            ],
        "keepNotMatched": True,
        "otaOrderNo": "exw240116172920466003",
        "tickets":
            [
                {
                    "arr": f"{arr}",
                    "arrTime": f"{arr_time}",
                    "birthDay": "1996-01-10",
                    "buildPrice": 0,
                    "cabinCode": f"{cabin}",
                    "certCode": "410185200201189869",
                    "certType": "ID",
                    "dep": f"{dep}",
                    "depTime": f"{dep_time}",
                    "flightNo": f"{flight_no}",
                    "fuelPrice": 0,
                    "gender": "FEMALE",
                    "mobile": "13783590698",
                    "name": "赵瑞凯",
                    "printPrice": 0,
                    "salePrice": 0,
                    "type": "ADU"
                }
            ]
    }

    # 签名生成
    time_millis = int(time.time() * 1000)
    text = f"{appkey}&{time_millis}&{secret}"
    sign = hashlib.md5(text.encode('utf-8')).hexdigest()

    # 构建请求
    headers = {
        "Content-Type": "application/json",
        "appKey": appkey,
        "sign": sign,
        "timestamp": str(time_millis)
    }

    """
    请求接口
    """
    max_tries = retry_num  # 最大尝试次数
    num_tries = 0  # 已尝试次数
    sleep_time2 = 1  # 设置等待时间
    result = ''
    while num_tries < max_tries:
        try:
            response = requests.post(url, headers=headers, json=req)
            result = response.text
            res_data = json.loads(result)
            # print(json.dumps(res_data))

            if res_data['content'] is not None:
                r_price = [price for price in res_data['content'] if
                           price['policyTypeDesc'] == '低价专享' and '高铁用户' in price['remark']]

                if len(r_price) > 0:
                    logger.info(f"【腾鸢去哪儿APP报价接口{account['username']}】结果: {str(r_price)}")
                    return r_price
                else:
                    logger.error(f"【腾鸢去哪儿APP报价接口{account['username']}】结果: {dep_time}/{flight_no}/{dep}/{arr}没有合适数据")
                    num_tries += 1
                    if num_tries >= max_tries:
                        # 如果已经尝试到最大次数，跳出循环，放弃重试
                        logger.error(f"重试{max_tries}次后仍然失败，放弃重试。")
                        break
                    # 打印日志，并且睡眠
                    logger.info(f"请求失败，休眠 {sleep_time2} 秒后进行第 {num_tries + 1} 次尝试。")
            else:
                logger.error(f"【腾鸢去哪儿APP报价接口{account['username']}】结果: {str(result)}")
                num_tries += 1
                if num_tries >= max_tries:
                    # 如果已经尝试到最大次数，跳出循环，放弃重试
                    logger.error(f"重试{max_tries}次后仍然失败，放弃重试。")
                    break
                # 打印日志，并且睡眠
                logger.info(f"请求失败，休眠 {sleep_time2} 秒后进行第 {num_tries + 1} 次尝试。")
        except (requests.exceptions.RequestException, json.JSONDecodeError) as e:
            logger.error(f"【腾鸢去哪儿APP报价接口{account['username']}】结果: {str(result)}")
            num_tries += 1
            if num_tries >= max_tries:
                # 如果已经尝试到最大次数，跳出循环，放弃重试
                logger.error(f"重试{max_tries}次后仍然失败，放弃重试。")
                break
            # 打印日志，并且睡眠
            logger.info(f"请求失败，休眠 {sleep_time2} 秒后进行第 {num_tries + 1} 次尝试。")
            logger.error(e)
            time.sleep(sleep_time2)


def task_function(tf_row):
    pr_dep_time = get_date_time(tf_row['出发日期'] + ' ' + tf_row['出发时间'])
    pr_arr_time = get_date_time(tf_row['到达日期'] + ' ' + tf_row['到达时间'])
    tf_row2 = dict(tf_row)
    tc_rp = send_request(tf_row2.get('航班号'), 'E', tf_row2.get('起飞'), tf_row2.get('到达'),
                         pr_dep_time, pr_arr_time)

    print(tc_rp)

    # 更新进度条
    progress_bar.update(1)

    if tc_rp is not None and len(tc_rp) > 0:
        count = 0
        for e in tc_rp:
            collection.insert_one(e)
            r_p_excel_df.at[tf_row.name, f'舱位{count}'] = e['cabinCode']
            r_p_excel_df.at[tf_row.name, f'价格{count}'] = e['cabinPrice']
            r_p_excel_df.at[tf_row.name, f'类型{count}'] = e['policyTypeDesc']
            r_p_excel_df.at[tf_row.name, f'描述{count}'] = e['remark']
            count = count + 1

        logger.info(f"报表数据：{tf_row}")


if __name__ == '__main__':
    retry_num = 3
    pr_dep_time = get_date_time('2024-04-17 10:35')
    pr_arr_time = get_date_time('2024-04-17 12:40')
    tc_rp = send_request('3U8043', 'E', 'CKG', 'NKG', pr_dep_time, pr_arr_time)

    # read_file = input("请输入读取文件名：")
    # write_file = input("请输入输出文件名：")
    # thread_num = int(input("请输线程数："))
    # retry_num = int(input("请输最大重试次数："))
    #
    # # 初始化日志配置
    # log_config()
    #
    # # 连接到MongoDB
    # client = MongoClient(f'mongodb://{quote_plus("admin")}:{quote_plus("mongo@yc66.com")}@192.168.110.135:27027/?authMechanism=DEFAULT&authSource=admin')
    # # 选择数据库
    # db = client['py_policy']
    # # 选择集合
    # collection = db['ty_qunar_app']
    #
    # # 相对文件路径
    # # current_dir = os.path.dirname(os.path.abspath(__file__))
    # # current_dir = '../docs/'
    # current_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
    # read_path = os.path.join(current_dir, f"{read_file}.xlsx")
    # write_path = os.path.join(current_dir, f"{write_file}.xlsx")
    #
    # # 读取excel文件
    # r_p_excel_file = pd.ExcelFile(read_path)
    # # 读取指定Sheet数据
    # r_p_excel_df = r_p_excel_file.parse('Sheet1')
    #
    # total_rows = len(r_p_excel_df)
    #
    # # 创建进度条
    # progress_bar = tqdm(total=total_rows, desc="执行进度", unit="次")
    #
    # # for index, row in r_p_excel_df.iterrows():
    # #     task_function(row)
    #
    # with concurrent.futures.ThreadPoolExecutor(max_workers=thread_num) as executor:
    #     for index, row in r_p_excel_df.iterrows():
    #         # task_function(row)
    #         executor.submit(task_function, row)
    #
    # # 关闭进度条
    # progress_bar.close()
    #
    # logger.info("开始生成excel文件...")
    # r_p_excel_df.to_excel(write_path, index=False)
